<template>
    <div class="pages stockcheckadd">
     <div class="pageLevel">
      <!-- 分几步 -->
        <div class="step">
         <el-steps :space="350" class="step-style" :active="active" finish-status="success" align-center>
         <el-step title="选择盘点模式" ></el-step>
         <el-step title="选择商品"></el-step>
         <el-step title="完成"></el-step>
        </el-steps>
        </div>
        
       <el-form  :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <!-- 选择盘点模式 -->
        <div v-show="active===1" class="commnStyle modestyle">
          <el-form-item label="盘点模式:" prop="inventoryMode">
               <el-radio-group v-model="ruleForm.inventoryMode">
               <el-radio label="0">盲盘</el-radio>
               <el-radio label="1">明盘</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="盘点类型:" prop="inventoryType">
               <el-radio-group v-model="ruleForm.inventoryType">
               <el-radio label="0">日盘</el-radio>
               <el-radio label="1">周盘</el-radio>
               <el-radio label="2">月盘</el-radio>
              </el-radio-group>
          </el-form-item>
          </div>
           <!-- 选择商品 -->
         <div v-show="active===2" class="commnStyle changeShop">
             <el-form-item label="选择盘点仓库:" label-width="100px">
                  <el-select filterable size="small" style="width:190px"  @change="warehouseChange" v-model="ruleForm.warehouse" placeholder="全部">
                   <el-option v-for="(item,index) in warehouseLists" :key="index" :label="item.repositoryName" :value="item.id"> </el-option>
                 </el-select>
                 <el-button type="primary" size="small" style="margin-left: 10px;"  @click="addShop">添加商品</el-button> 
             </el-form-item>
             <el-button type="primary" size="small"   @click="deleteInventoryMany">撤出盘点</el-button>
             <!-- 选择的商品表格 -->
             <div class="tableMain" >
                <el-table :data="goodsList" stripe style="width: 80%" @selection-change="changeFun_good">
                 <el-table-column type="selection" width="55" align="center"></el-table-column>
                 <el-table-column prop="goodsCode"  label="商品货号" align="center">
                 </el-table-column>
                 <el-table-column prop="barCode" label="商品条码" align="center">
                 </el-table-column>
                 <el-table-column prop="name" label="商品名称" align="center">
                 </el-table-column>
                 <el-table-column prop="parameter" label="规格型号" align="center">
                   <template slot-scope="scope">
                     <div v-for="(item, index) in  scope.row.parameter" :key="index">
                       <span v-if="item!=null">{{item.paramName}} :</span>
                       <span v-if="item!=null">{{item.paramValue}} </span>
                    </div>
                  </template>
                 </el-table-column>
                 <!-- 集团订单新加功能5/31 -->
                <el-table-column prop="dateInProduced"  label="生产日期" align="center" width="100">
                  <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                </el-table-column>
                 <el-table-column prop="goodsBatchNumber" label="商品批次" align="center">
                   <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                 </el-table-column>
                 <el-table-column prop="goodsUnit" label="单位" align="center">
                 </el-table-column>
                 <el-table-column prop="name" align="center" label="操作" width="180">
                    <template slot-scope="scope">
                       <el-button size="small" @click="deleteInventory(scope.$index,scope.row)" type="text" class="addDetail">撤出盘点</el-button>
                    </template>
                 </el-table-column>
               </el-table> 
             </div> 
         </div>
         <!-- 完成 -->
         <div v-show="active===3" class="commnStyle complete">
              <el-form-item label="盘点模式:">
                <span>{{inventoryMode}}</span>
             </el-form-item>
             <el-form-item label="盘点类型:">
                <span>{{inventoryType}}</span>
             </el-form-item>
             <el-form-item label="盘点仓库:">
                <span>{{warehouse}}</span>
             </el-form-item>
              <el-form-item label="盘点商品:">
             </el-form-item>
              <div class="tableMain">
                <el-table :data="completeGoodsList" stripe style="width: 80%">
                 <el-table-column prop="goodsCode"  label="商品货号" align="center">
                 </el-table-column>
                 <el-table-column prop="barCode" label="商品条码" align="center">
                 </el-table-column>
                 <el-table-column prop="name" label="商品名称" align="center">
                 </el-table-column>
                 <el-table-column prop="parameter" label="规格型号" align="center">
                   <template slot-scope="scope">
                     <div v-for="(item, index) in  scope.row.parameter" :key="index">
                       <span v-if="item!=null">{{item.paramName}} :</span>
                       <span v-if="item!=null">{{item.paramValue}} </span>
                    </div>
                  </template>
                 </el-table-column>
                  <!-- 集团订单新加功能5/31 :formatter="dateInProduced"-->
                <el-table-column prop="dateInProduced"  label="生产日期" align="center" width="100">
                  <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                 </el-table-column>
                 <el-table-column prop="goodsBatchNumber" label="商品批次" align="center">
                   <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                 </el-table-column>
                 <el-table-column prop="goodsUnit" label="单位" align="center">
                 </el-table-column>
               </el-table> 
             </div>

         </div>
          <div class="buttonstyle">
           <el-button size="small" style="margin-top: 12px;"  @click="cancel">取消</el-button>
           <el-button type="primary" size="small"  style="margin-top: 12px;" v-if="active==2||active==3"  @click="upper">上一步</el-button>
           <el-button type="primary" size="small" style="margin-top: 12px;" v-if="active==1||active==2"  @click="next(false)">下一步</el-button>
           <el-button type="primary" size="small" style="margin-top: 12px;" v-if="active==3"  @click="completeSubmission">完成</el-button>
         </div>
      </el-form>
      <!-- 商品弹窗 -->
      <el-dialog title="添加商品" class="addshopname dialogshopname" :visible.sync="dialogTableVisible_good" :closeOnClickModal='false' :closeOnPressEscape='false' width="70%">
           <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
            <div class="tableSearch tableSearchs">
            <el-form label-width="80px" class="demo-ruleForm">
             <el-form-item label="商品名称:" label-width="">
               <el-input class="input" v-model="dialogShop.shopName" size="small" placeholder="输入商品名称或商品条码"></el-input>
             </el-form-item>
             <el-form-item label="商品品牌:" label-width="">
               <el-select  size="small" filterable remote reserve-keyword :remote-method="brandMethod"  v-model="dialogShop.commodityBrand" placeholder="请先选择商品品牌">
                 <el-option v-for="(item,index) in commodityBrandList" :key="index" :label="item.name" :value="item.id"> </el-option>
               </el-select>
             </el-form-item>
             <el-form-item label="商品分类:">
                <el-cascader size="small"  change-on-select  expand-trigger="hover" :options="commodityCategoryfunList" v-model="dialogShop.commodityCategory" >
                </el-cascader>
             </el-form-item>
             <el-form-item label="商品批次:" label-width="">
               <el-select  size="small" filterable remote reserve-keyword :remote-method="goodsBatchNumbeMethod" v-model="dialogShop.commodityBatches" placeholder="请先选择商品品牌">
                   <el-option   label='全部' value=''> </el-option>
                   <!-- v-if="item.goodsBatchNumber!=''" -->
                 <el-option  v-for="(item,index) in commodityCategoryList" v-if="item.goodsBatchNumber!=''" :key="index" :label="item.goodsBatchNumber" :value="item.goodsBatchNumber"> </el-option>
               </el-select>
             </el-form-item>
             <el-form-item label="" label-width="20px">
               <el-button @click="dialogSearch()" size="small" type="primary">查询</el-button>
             </el-form-item>
           </el-form>
          </div>
          <el-button type="primary" size="small"   @click="dialogJoinInventoryMany()">参加盘点</el-button>
          <el-button type="primary" size="small"   @click="dialogDeleteInventoryMany(dialogGoodsList)">撤出盘点</el-button>
             <!-- 选择的商品表格 -->
             <div class="tableMain">
                <el-table :data="dialogGoodsList" tooltip-effect="dark" ref="dialogChooseData" stripe style="width: 100%" @selection-change="dialogchangeFun_good">
                  <!-- :selectable="puStatus" -->
                  <el-table-column type="selection" width="55" align="center" :selectable="puStatus"></el-table-column>
                 <el-table-column prop="goodsCode"  label="商品货号" align="center">
                 </el-table-column>
                 <el-table-column prop="barCode" label="商品条码" align="center">
                 </el-table-column>
                 <el-table-column prop="name" label="商品名称" align="center">
                 </el-table-column>
                 <el-table-column prop="parameter" label="规格型号" align="center">
                   <template slot-scope="scope">
                     <div v-for="(item, index) in  scope.row.parameter" :key="index">
                       <span v-if="item!=null">{{item.paramName}} :</span>
                       <span v-if="item!=null">{{item.paramValue}} </span>
                    </div>
                  </template>
                 </el-table-column>
                 <!-- 集团订单新加功能5/31 -->
                <el-table-column prop="dateInProduced"  label="生产日期" align="center" width="100">
                    <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                </el-table-column>
                 <el-table-column prop="goodsBatchNumber" label="商品批次" align="center">
                   <template slot-scope="scope" >
                     <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
                     <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
                    </template>
                 </el-table-column>
                 <el-table-column prop="goodsUnit" label="单位" align="center">
                 </el-table-column>
                 <el-table-column prop="name" align="center" label="操作" width="180">
                    <template slot-scope="scope">
                       <el-button :disabled="scope.row.type=='0'" v-if="scope.row.isShow==true" size="small"  type="text" class="addDetail" @click="dialogDeleteInventory(scope.$index,scope.row)">撤出盘点</el-button>
                       <el-button :disabled="scope.row.type=='0'" v-if="scope.row.isShow==false" size="small" type="text" class="addDetail" @click="dialogJoinInventory(scope.$index,scope.row)">参加盘点</el-button>
                    </template>
                 </el-table-column>
               </el-table> 
              
             </div> 
              <div style="text-align:right;margin-top:20px;">
                 <el-button size="small" @click="dialogTableVisible_good = false">取 消</el-button>
                 <el-button size="small" type="primary" @click="dialogSure">确 定</el-button>
                </div>
      </el-dialog>
     
    </div>
   </div>
</template>
<script>
import { mapState } from "vuex";
import util from '@/util'
import { getRepositoryListPage ,selectByGoodsId,getGoodsClassifyTreeList,findGoodsRepByGoodsId,findGoodsByBarCode,addInventory} from "@/api";
export default {
    computed: mapState(["merchantId","power","companyName","userId"]),
    data() {
      return {
        active: 1,//默认选中
        ruleForm:{
          inventoryMode:"0",//盘点模式
          inventoryType:"0",//盘点类型
          warehouse:"",//盘点仓库
        },
        rules:{},
        warehouseLists:[],//盘点仓库
        goodsList:[],//商品列表
        chooseData:[],//选择的商品
        /*------商品弹框开始------*/
        dialogTableVisible_good:false,//添加商品弹窗
        dialogShop:{
          shopName:"",//商品弹窗商品名称
          commodityBrand:"",//品牌
          commodityCategory:[""],//分类
          commodityBatches:"",//批次
        },
        commodityBrandList:[],//品牌数据
        commodityCategoryfunList:[],//分类数据
        commodityCategoryList:[],//批次数据
        dialogGoodsList:[],//列表数据
        dialogChooseData:[],//弹窗选择的数据
        JoinShop:[],//参与盘点的商品
       /* -------商品弹框结束-----*/
        completeGoodsList:[],//完成后的商品
        inventoryMode:"",//盘点模式
        inventoryType:"",//盘点类型
        warehouse:"",//盘点仓库
        brandInfo:"",//品牌输入的值
        goodsBatchNumbeInfo:""//批次输入的值
      };
    },
    mounted(){
       this.warehouseList()
    },
    methods: {
          //转时间戳
      dateInProduced(row, column) {
       return util.foryear(row.dateInProduced)
     },
      // 判断是不是已经用过的商品
      puStatus(row, index) {
        if(row.type!=undefined){
          return false;
        }else{
          return true;
        }
    },
     // 添加商品按钮
     addShop(){
       if(this.ruleForm.warehouse==""){
          this.$message({
             type: "error",
            message: "请先选择盘点仓库!"
          }); 
       }else{
         this.dialogTableVisible_good=true
         this.commodityBrand()//品牌接口
         this.commodityCategoryfun()//分类接口
         this.shopCategory()//商品批次
         this.dialogGetGoods()//弹窗列表数据
       }
     },
     deleteInventory(index,rows){
         this.JoinShop.forEach(item=>{
           if(rows.isBatch=='1'){
             if(item.id==rows.id&&item.goodsBatchNumber==rows.goodsBatchNumber){
             this.$set(item,"isShow",false);
             this.goodsList.splice(index, 1);
            }
           }else{
             if(item.id==rows.id){
              this.$set(item,"isShow",false);
              this.goodsList.splice(index, 1);
              }
            }
          
         })
     },
     //  多选撤出盘点
     deleteInventoryMany(){
         if(this.chooseData.length>0){
            let self = this;
            this.goodsList = this.goodsList.filter(function(item) {
            return self.chooseData.indexOf(item) == -1;
           });
         }else{
            this.$message({
             type: "error",
            message: "请先选择撤出盘点的商品!"
          }); 
         }
         this.JoinShop.forEach(item=>{
            this.chooseData.forEach(ele=>{
               if(item.isBatch=='1'){
                  if(item.id==ele.id&&item.goodsBatchNumber==ele.goodsBatchNumber){
                  this.$set(item,"isShow",false);
                }
               }else{
                  if(item.id==ele.id){
                     this.$set(item,"isShow",false);
                  }
               }
               
            })
          
         })
      },
     //  选择商品数组
     changeFun_good(val) {
       if (val) {
        this.chooseData = val;
      } else {
        this.chooseData = [];
        }
    },
     // 仓库列表
     warehouseList() {
      getRepositoryListPage({
          shopId: this.merchantId,
          status: "0",
          openingInventoryState:"1"
      }).then(res => {
        this.warehouseLists=res.data.list 
      });
    },
     /* -------商品弹窗中函数开始-------*/
     // 
     brandMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.brandInfo = query;
          this.commodityBrand(this.dialogShop.commodityBrand);
          }, 200);
      } else {
        this.commodityBrand(this.dialogShop.commodityBrand);
          
      }
    },
     // 商品品牌
    commodityBrand() {
      selectByGoodsId({
        shopId:this.merchantId,
        repositoryId: this.ruleForm.warehouse,
        keyword:this.brandInfo,
        type:"0",
        }).then(res => {
          let a={
           id:"",
           name:"全部",
          }
        res.data.list.unshift(a)
        this.commodityBrandList = res.data.list;
      })
    },
     // 商品品类
    commodityCategoryfun() {
      getGoodsClassifyTreeList().then(res => {
        let a={
           value:"",
           label:"全部",
          }
        res.data.unshift(a)
        this.commodityCategoryfunList = res.data;
      });
    },
     goodsBatchNumbeMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.goodsBatchNumbeInfo = query;
          this.shopCategory(this.dialogShop.commodityBatches);
          }, 200);
      } else {
        this.shopCategory(this.dialogShop.commodityBatches);
          
      }
    },
      // 商品批次
    shopCategory() {
      findGoodsRepByGoodsId({
        repositoryId:this.ruleForm.warehouse,
        goodsBatchNumber:this.goodsBatchNumbeInfo,
        pageSize:"50",
        pageNum:"1",
        }).then(res => {
        this.commodityCategoryList = res.data.list;
         this.commodityCategoryList=this.uniqs(this.commodityCategoryList)
      })
    },
     // 去重
    uniqs(arr) {
      let newArr = [arr[0]];
      for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
          if (
            arr[i].goodsBatchNumber === newArr[j].goodsBatchNumber
          ) {
            repeat = true;
            break;
          } else {
          }
        }
        if (!repeat) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    // 商品列表数据
     dialogGetGoods(pageSize, pageNum) {
     let primaryClassifyId = this.dialogShop.commodityCategory[this.dialogShop.commodityCategory.length-1] || '';
      let data = {
        keyword: this.dialogShop.shopName,
        goodsLabelId: this.dialogShop.commodityBrand,
        primaryClassifyId: primaryClassifyId,
        goodsBatchNumber: this.dialogShop.commodityBatches,
        repositoryId:this.ruleForm.warehouse,
        shopId: this.merchantId,
      };
      findGoodsByBarCode(data).then(res => {
        if(res.code==200){
          this.dialogGoodsList = res.data.list;
        this.dialogGoodsList.forEach(item=>{
          this.$set(item,"isShow",false)
          if(item.isBatch=="1"){
             item.dateInProduced=util.foryear(item.dateInProduced)
          }
        })
        }else{
           this.dialogGoodsList=[]
        }
        if(this.JoinShop.length>0){
          this.JoinShop.forEach(item=>{
           if(item.isShow==true){
             this.dialogGoodsList.unshift(item)
          }
          })
          this.dialogGoodsList=this.uniq(this.dialogGoodsList)
        }
      });
    },
    dialogchangeFun_good(val){
       if (val) {
         this.dialogChooseData = val;
     } else {
        this.dialogChooseData = [];
        }

    },
    // 搜索
    dialogSearch(){
      this.dialogGetGoods()
       },
    // 参与盘点
    dialogJoinInventoryMany(rows){
        this.dialogChooseData.forEach(item=>{
          this.$set(item,"isShow",true)
        })
         this.JoinShop=this.JoinShop.concat(this.dialogChooseData)
         this.JoinShop=this.uniq(this.JoinShop)
     },
     dialogJoinInventory(index,rows){
      this.$set(rows,"isShow",true)
       this.JoinShop.push(rows)
     },
    // 去重
    uniq(arr) {
      let newArr = [arr[0]];
      for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
          if (
            arr[i].id === newArr[j].id && arr[i].goodsBatchNumber === newArr[j].goodsBatchNumber
          ) {
            repeat = true;
            break;
          } else {
          }
        }
        if (!repeat) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    // 撤出盘点
    dialogDeleteInventoryMany(rows){
        this.dialogChooseData.forEach(item=>{
          this.$set(item,"isShow",false)
        })
     },
     dialogDeleteInventory(index,rows){
       this.$set(rows,"isShow",false)
     },
    // 商品最终选择的值
    dialogSure(){
      let goosLists=[]
      this.dialogGoodsList.forEach(item=>{
        if(item.isShow==true){
          goosLists.push(item)
        }
      })
      this.goodsList=this.goodsList.concat(goosLists)
      if(goosLists.length==0){
        this.$message({
             type: "error",
             message: "请先选择盘点的商品!"
          }); 
        
      }else{
         this.dialogTableVisible_good=false
         this.goodsList=this.uniq(this.goodsList)
        //  this.JoinShop.forEach(item=>{
        //      this.$set(item,"isShow",false)
             
        //  })
      }
    },
     /* -------商品弹窗中函数结束-------*/
    //  仓库改变时
     warehouseChange(val){
       if(val){
           this.goodsList=[]
           this.JoinShop.forEach(item=>{
           this.$set(item,"isShow",false);
          })
       }
     },
      // 上一步
      upper(){
        this.active--
      },
     // 下一步
      next(name) {
       if(this.active==1&&this.ruleForm.inventoryMode!=''){
           this.active++
         }else if(this.active==2&&this.goodsList.length==0){
              this.$message({
              type: "error",
               message: "请先选择盘点的商品!"
            }); 
            return false
         }else{
            this.active++
         }
        //  if (this.active++ > 3) this.active = 1;
         if(this.active=="3"){
          this.warehouseLists.forEach(item=>{
            if(this.ruleForm.warehouse==item.id){
              this.warehouse=item.repositoryName
            }
          })
          if(this.ruleForm.inventoryMode=="0"){
              this.inventoryMode="盲盘"
          }else{
            this.inventoryMode="明盘"
          }
           if(this.ruleForm.inventoryType=="0"){
              this.inventoryType="日盘"
          }else if(this.ruleForm.inventoryType=="1"){
              this.inventoryType="周盘"
          }else{
              this.inventoryType="月盘"
          }
          this.completeGoodsList=this.goodsList
        }
      },
      // 完成
      completeSubmission(name, param){
        let changeList=[]
        this.JoinShop.forEach(ele=>{
             if(ele.isShow==true){
                changeList.push(ele)
             }
        })
        changeList=this.uniq(changeList)
        this.JoinShop=changeList
        let goodsList = this.JoinShop.map(function(item) {
        return {
          goodsId: item.id,
          goodsName: item.name,
          goodsNum: item.goodsNum,
          goodsBatchNumber: item.goodsBatchNumber,
          dateInProduced:item.dateInProduced,
          goodsUnit: item.goodsUnitId,
          goodsOrganizationSkuId: item.id,
          barCode: item.barCode,
          goodsCode: item.goodsCode,
          goodsPrice: item.purchasePrice,
          goodsSpec: item.parameter,
          isBatch: item.isBatch
        };
      });
        let invebtryAdd={
          creater:this.userId,
          shopId:this.merchantId,
          shopName:this.companyName,
          inventoryPattern:this.ruleForm.inventoryMode,
          inventoryType:this.ruleForm.inventoryType,
          inventoryPattern:this.ruleForm.inventoryMode,
          inventoryStatus:'0',
          goodsInventoryDetails:JSON.stringify(goodsList),
          warehouseId:this.ruleForm.warehouse,
        }
        addInventory(invebtryAdd).then(res=>{
           if(res.code==200){
              history.back();
           }
        })
        //  util.routerTo('/order-center/stock-management/stock-checkList')
      },
      // 取消
      cancel(){
         history.back();
      }
    }
}
</script>
<style lang="" scoped>
.stockcheckadd .step{
    width:100%;
    margin:0 auto;
    margin-top:40px;
    height:100px;
}
.stockcheckadd .step-style{
    width:90%;
    margin:0 auto;
}
.commnStyle{
    margin-left:120px;
}
.buttonstyle{
    width:80%;
    text-align: right;
    margin-top:100px;
}
.changeShop .tableMain{
    margin-top:30px;
}

</style>
<style lang="">
.stockcheckadd .el-step__icon-inner{
    display:none !important;
}
.dialogshopname .el-input{
    width:120px !important;
}
</style>